package com.example;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.scene.control.Alert;
import javafx.scene.input.MouseButton;
import javafx.scene.control.TableRow;

import java.sql.SQLException;
import java.util.List;
import java.util.HashSet;
import java.util.Set;

public class StudentViewGradesController implements StudentSubController {

    @FXML
    private ComboBox<String> semesterFilterComboBox;
    @FXML
    private ComboBox<String> courseTypeFilterComboBox;
    @FXML
    private Button filterButton;
    @FXML
    private TableView<Grade> gradesTable;
    @FXML
    private Button backButton;

    private Stage primaryStage;
    private StudentController studentController;
    private User currentUser;
    private GradeDAO gradeDAO;
    private ObservableList<Grade> allGrades;

    @Override
    public void setPrimaryStage(Stage primaryStage) {
        this.primaryStage = primaryStage;
    }

    @Override
    public void setStudentController(StudentController studentController) {
        this.studentController = studentController;
    }

    public void setCurrentUser(User user) {
        this.currentUser = user;
        loadGrades();
    }

    @FXML
    public void initialize() {
        gradeDAO = new GradeDAO();
        setupTable();

        // 初始化筛选下拉框（可以在加载数据后填充实际值）
        semesterFilterComboBox.getItems().add("全部");
        courseTypeFilterComboBox.getItems().add("全部");

        // 添加表格行双击事件监听器 (已移除)
        // gradesTable.setRowFactory(tv -> {
        //     TableRow<Grade> row = new TableRow<>();
        //     row.setOnMouseClicked(event -> {
        //         if (! row.isEmpty() && event.getButton()==MouseButton.PRIMARY 
        //              && event.getClickCount() == 2) {
        //             Grade clickedGrade = row.getItem();
        //             handleViewDetails(clickedGrade);
        //         }
        //     });
        //     return row;
        // });
    }

    private void setupTable() {
        // 设置表格列
        TableColumn<Grade, String> courseNameCol = new TableColumn<>("课程名称");
        courseNameCol.setCellValueFactory(new PropertyValueFactory<>("courseName"));

        TableColumn<Grade, Double> scoreCol = new TableColumn<>("成绩");
        scoreCol.setCellValueFactory(new PropertyValueFactory<>("score"));

        TableColumn<Grade, String> semesterCol = new TableColumn<>("学期");
        semesterCol.setCellValueFactory(new PropertyValueFactory<>("semester"));

        TableColumn<Grade, String> courseTypeCol = new TableColumn<>("课程类型");
        courseTypeCol.setCellValueFactory(new PropertyValueFactory<>("courseType"));

        gradesTable.getColumns().addAll(courseNameCol, scoreCol, semesterCol, courseTypeCol);
    }

    private void loadGrades() {
        if (currentUser != null) {
            try {
                allGrades = FXCollections.observableArrayList(gradeDAO.getGradesByStudentUsername(currentUser.getUsername()));
                gradesTable.setItems(allGrades);
                populateFilterComboBoxes(allGrades);
            } catch (SQLException e) {
                e.printStackTrace();
                showAlert(Alert.AlertType.ERROR, "数据库错误", "加载成绩失败：" + e.getMessage());
            }
        } else {
             showAlert(Alert.AlertType.ERROR, "错误", "当前用户信息未加载，无法加载成绩。");
        }
    }

    private void populateFilterComboBoxes(List<Grade> grades) {
        Set<String> semesters = new HashSet<>();
        Set<String> courseTypes = new HashSet<>();

        for (Grade grade : grades) {
            semesters.add(grade.getSemester());
            courseTypes.add(grade.getCourseType());
        }

        semesterFilterComboBox.getItems().addAll(semesters);
        courseTypeFilterComboBox.getItems().addAll(courseTypes);
    }

    @FXML
    private void handleFilter() {
        String selectedSemester = semesterFilterComboBox.getValue();
        String selectedCourseType = courseTypeFilterComboBox.getValue();

        if (currentUser != null) {
            try {
                List<Grade> filteredGrades = gradeDAO.getFilteredGradesForStudent(
                    currentUser.getUsername(),
                    selectedSemester,
                    selectedCourseType
                );
                gradesTable.setItems(FXCollections.observableArrayList(filteredGrades));
            } catch (SQLException e) {
                e.printStackTrace();
                showAlert(Alert.AlertType.ERROR, "数据库错误", "筛选成绩失败：" + e.getMessage());
            }
        }
    }

    @FXML
    private void handleBack() {
        if (studentController != null) {
            // 返回学生主界面默认视图
            studentController.showStudentHomeView();
        } else {
            System.err.println("studentController is null");
        }
    }

    private void showAlert(Alert.AlertType alertType, String title, String message) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
} 